/**
 * Copyright (c) 2012-2014 All Rights Reserved.
 */
package com.easy.framwork;

import java.util.Map;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.easy.framwork.datasoruce.C3p0DatasourceProvider;
import com.easy.framwork.datasoruce.DatasourceProvider;
import com.easy.framwork.exceptions.IllegalArgException;
import com.easy.framwork.utils.PropertiesUtils;
import com.easy.framwork.utils.ReflectUtils;

/**
 * 
 * @author wy
 * @version v 0.1 2014-1-1 下午12:50:58 wy Exp $
 */
public class FrameworkHolder {

    private static final Logger log = LoggerFactory.getLogger(FrameworkHolder.class);

    /** 配置文件 */
    public static final String CONFIG_PRO = "easy.properties";

    /** 单例变量 */
    private static FrameworkHolder frameworkHolder = null;

    /** 数据源提供 class */
    private Class<? extends DatasourceProvider> datasourceProviderClass = C3p0DatasourceProvider.class;

    /** 数据源 */
    private DataSource dataSource;

    /**
     * 保护构造
     */
    private FrameworkHolder() {

    }

    /**
     * 获取实例对象
     * 
     * @return
     */
    public static FrameworkHolder getInstance() {
        if (frameworkHolder == null) {
            synchronized (CONFIG_PRO) {
                if (frameworkHolder != null) {
                    return frameworkHolder;
                }
                frameworkHolder = new FrameworkHolder();
                frameworkHolder.initEasyConfig();
            }
        }
        return frameworkHolder;
    }

    /**
     * 获取DatasourceProvider类
     * 
     * @return
     */
    public Class<? extends DatasourceProvider> getDatasourceProviderClass() {
        return datasourceProviderClass;
    }

    /**
     * 获取数据源
     * 
     * @return
     */
    public DataSource getDataSource() {
        return this.dataSource;
    }

    /**
     * 初始化配置
     */
    @SuppressWarnings("unchecked")
    private void initEasyConfig() {
        Map<String, String> configMap = PropertiesUtils
            .loadResourceFormClassPath(FrameworkHolder.CONFIG_PRO);
        String datasourceProvider = configMap.get("config.datasource.provider");
        try {
            Class<?> clazz = Class.forName(datasourceProvider);
            if (!DatasourceProvider.class.isAssignableFrom(clazz)) {
                throw new IllegalArgException("class " + datasourceProvider
                                              + "must implements DatasourceProvider");
            }
            datasourceProviderClass = (Class<? extends DatasourceProvider>) clazz;
            DatasourceProvider dsp = ReflectUtils.newInstance(datasourceProviderClass);
            dataSource = dsp.getDataSource();
        }
        catch (ClassNotFoundException e) {
            log.error("class {} not find,:{}", datasourceProvider, e);
            throw new IllegalArgException("can not find class " + datasourceProvider);
        }

        String basePackage = configMap.get("config.action.basePackage");

    }
}
